package com.tian.service.impl;

import com.tian.entity.RetryMessage;
import com.tian.mapper.RetryMessageMapper;
import com.tian.producer.ChargingDataRegistryProducer;
import com.tian.service.ChargingDataJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@code @description:} 充电实时数据失败消息
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-26 16:12
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class ChargingDataJobServiceImpl implements ChargingDataJobService {
    @Resource
    private RetryMessageMapper retryMessageMapper;
    @Resource
    private ChargingDataRegistryProducer chargingDataRegistryProducer;
    private static final int PAGE_SIZE = 50;

    @Override
    public void execute() {
        int count = retryMessageMapper.countByType(1);
        if (count == 0) {
            log.info("充电实时数据失败消息：没有需要重试的数据");
            return;
        }
        int countPage = count / PAGE_SIZE + 1;
        for (int i = 0; i < countPage; i++) {
            List<RetryMessage> retryMessageList = retryMessageMapper.pageList(1, i * PAGE_SIZE, PAGE_SIZE);
            for (RetryMessage retryMessage : retryMessageList) {
                // 重试次数超过3次，则不再重试，这个次数也可以调整为配置文件中
                if (retryMessage.getRetriedTimes() >= 3) {
                    //发告警邮件
                    log.info("充电实时数据失败消息：重试次数超过3次，不再重试");
                    continue;
                }
                // 补发消息
                chargingDataRegistryProducer.sendMessage(retryMessage);
            }
        }

    }
}
